#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import time
import datetime
import os
import oauth
import simplejson
import urllib
import random
from xml.dom import minidom
from xml.etree.ElementTree import *
"""

"""
CONSUMER_KEY = 'WcAOb9F3CtXp9VsJTBy5kA'
CONSUMER_SECRET_KEY = 'r2jdKZ2zQw3lJhXvN3GfyBX99GstOHw67AMwQjr80'
ACCESS_TOKEN = '229879833-ik3Q8doFRQKKi6WQ2pp1KTP9mGewhQTWSfETFfqX'
ACCESS_TOKEN_SECRET = 'zcgD74kegyDf8RuOVCODyJKn394GZzQUbYsauynydsI'

class Speech(webapp.RequestHandler):
    
    def get(self):
        client = oauth.TwitterClient(CONSUMER_KEY, CONSUMER_SECRET_KEY, None)
        
        boo = ''
        from urllib import urlopen
        f = urlfetch.fetch('http://www.cooking-korea.com/rss/new.rdf')
        file=urlopen('http://www.kokin.rr-livelife.net/rss/rss20.php')
        xml = parse(file)
        #xdoc = minidom.parseString(f.content)
        root = xml.getroot()
        items = xml.findall('//item')
        #print xml.find('//item')
        lists = []
        for item in items:
            #print item.getiterator()
            hash = {}
            for node in item.getiterator():
                #print node.text
                hash[node.tag] = node.text
            lists.append(hash)
        #print len(lists)
        message = lists[random.randint(1,len(lists)-1)]["description"]
        #message = urllib.quote(message.encode("utf-8"));
        param = {'status': message.encode("utf-8") + str(datetime.datetime.now()) + '+α DB'}
        #print param["status"];
        #print message
        
        try:
            res = client.make_request('http://api.twitter.com/1/statuses/update.json',
                            token=ACCESS_TOKEN,
                            secret=ACCESS_TOKEN_SECRET,
                            additional_params=param,
                            method='POST')
            #print res.status_code
            if res.status_code != 200:
                logging.warning('Failed to post a message to twitter. status_code: %d' \
                                % res.status_code)
                self.response.out.write('Error Status:' + res.status_code)
                self.response.headers['Content-Type'] = 'application/json'
            self.response.out.write(res.content)
        except Exception, e:
            logging.error(e)
            


application = webapp.WSGIApplication([('/speech', Speech)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
